<?php
// directory that report text files are in
$REPORTS_DIR = 'reports';

// $langs array converts country codes to full names
require('langs.php');

// arrays for filtering
$valid_dates = array();
if(is_array($_POST['chk_dates'])) $valid_dates = $_POST['chk_dates'];
$all_dates = array();
$valid_apps = array();
if(is_array($_POST['chk_apps'])) $valid_apps = $_POST['chk_apps'];
$valid_regions = array();
if(is_array($_POST['chk_regions'])) $valid_regions = $_POST['chk_regions'];
$valid_countries = array();
foreach($valid_regions as $vr) {
	if(is_array($regions[$vr])) {
		foreach($regions[$vr] as $cname)
			$valid_countries[] = $cname;
	}
}

// find report text files and read them
$files = array();
$d_entries = scandir($REPORTS_DIR);
foreach($d_entries as $f) {
	$fullname = $REPORTS_DIR . '/' . $f;
	if (is_file($fullname) and strtolower(substr($f,-4)) == '.txt') {
		$d = split('_',$f);
		$d = $d[4];
		$d = strtotime( substr($d,4,2) . '/' . substr($d,6,2) . '/' . substr($d,0,4) );
		if(empty($valid_dates) or in_array($d, $valid_dates))
			$files[$d] = file_get_contents($fullname);
		$all_dates[] = $d;
	}
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>iTunes App Store Sales Reports</title>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript">
// <![CDATA[
function bindRows() {
	var n = 0;
	while(row = document.getElementById("r" + n)) {
		row.onmouseover = function(){ this.className = 'rowOver'; };
		row.onmouseout = function(){ this.className = ''; };
		n++;
	}
}
// ]]>
</script>
</head>
<body onload="bindRows()">
<?php
// temporary output buffer
$echo = '';

// parse a single daily report file and organize by app and country
$all_apps = array();
function parse_daily_report($s) {
	global $all_apps, $valid_countries, $valid_apps;
	$lines = split("\n",$s);
	unset($lines[0]);	// get rid of first line column headers
	$apps = array();
	$totals = array();
	foreach($lines as $l) {
		$cols = split("\t",$l);
		if (strlen(trim($cols[6])) > 0) {
			if(empty($valid_apps) or in_array($cols[6],$valid_apps)) {
				// e.g. $apps['MyApp']['US'] = 142 units;
				$apps[$cols[6]][$cols[14]] += intval($cols[9]);
				if(empty($valid_countries) or in_array($cols[14],$valid_countries))
					$totals[$cols[6]] += intval($cols[9]);
				else $totals[$cols[6]] += 0;
			}
			if(!array_key_exists($cols[6], $all_apps))
				$all_apps[$cols[6]] = 0;
		}
	}
	return array('apps' => $apps, 'totals' => $totals);
}


$echo .= '<p>&nbsp;</p><table class="t1"><tr class="h1"><td>&nbsp;</td>';
$units = array();
// write date headers
foreach($files as $d => $s) {
	$units[$d] = parse_daily_report($s);
	$echo .= '<td colspan="' . count($units[$d]['totals']) . '">' . date('M d, Y',$d) . '</td>';
}
$echo .= '</tr><tr class="h2"><td class="h1">&nbsp;</td>';
// write app name headers
$class = '';
foreach($files as $d => $s) {
	$apps = array_keys($units[$d]['totals']);
	sort($apps);
	if($class == '') $class =  ' class="t3"';
	else $class = '';
	foreach($apps as $app) {
		$echo .= '<td' . $class . '>' . $app . '</td>';
	}
}
$echo .= "</tr>\n";
// write unit count for each country for each day for each app
$rownum = 0;
foreach($langs as $cc => $cname) {
	// filter validcountries
	if (!empty($valid_countries) and !in_array($cc,$valid_countries)) continue;
	
	// example array hierarchy: $units['Oct10th']['apps']['MyApp']['US'] = 1234
	$row = '<tr id="r' . $rownum . '"><td class="h1" title="' . $cc . '">' . $cname . '</td>';
	$total_units = 0;
	$class = '';
	foreach($units as $d => $apps) {
		$apps = array_keys($apps['apps']);
		sort($apps);
		foreach($apps as $app) {
			$num = $units[$d]['apps'][$app][$cc];
			$row .= '<td' . $class . '>' . $num . '</td>';
			$total_units += intval($num);
		}
		if($class == '') $class = ' class="t2"';
		else $class = '';
	}
	if($total_units > 0) {
		$echo .= $row . "</tr>\n";
		$rownum++;
	}
}
// write totals for each day for each app
$echo .= '<tr class="h3"><td><b>TOTAL</b></td>';
$class = '';
foreach($units as $d => $apps) {
	// example array hierarchy: $units[$d]['totals']['MyApp'] = 1234
	$apps = array_keys($apps['totals']);
	sort($apps);
	foreach($apps as $app) {
		$echo .= '<td' . $class . '>' . intval($units[$d]['totals'][$app]) . '</td>';
	}
	if($class == '') $class = ' class="t2"';
	else $class = '';
}
$echo .= '</tr></table>';





// TOP FORM WITH DATE/APP/REGION CHECKBOXES
echo '<form action="" method="post">';

// select daily reports
echo '<div class="topform"><span>';
echo '&gt;&gt; ' . count($all_dates) . ' Daily Reports Found</span><div';
if(count($all_dates) > 10) echo ' class="scroll"';	// if more than 10 daily reports, limit height
echo '>';
foreach($all_dates as $d) {
	echo '<input type="checkbox" name="chk_dates[]" value="' . $d . '"';
	if(empty($valid_dates) or in_array($d,$valid_dates)) echo ' checked="checked"';
	echo ' /> ' . date('M d, Y', $d) . '<br />';
} echo '</div></div>';

// select apps
$all_apps = array_keys($all_apps);
sort($all_apps);
echo '<div class="topform"><span>';
echo '&gt;&gt; ' . count($all_apps) . ' Apps Found</span><div>';
foreach($all_apps as $a) {
	echo '<input type="checkbox" name="chk_apps[]" value="' . $a . '"';
	if(empty($valid_apps) or in_array($a,$valid_apps)) echo ' checked="checked"';
	echo ' /> ' . $a . '<br />';
} echo '</div></div>';

// select countries
echo '<div class="topform"><span>';
echo '&gt;&gt; ' . count($regions) . ' Regions</span><div>';
foreach($regions as $reg => $arr) {
	echo '<input type="checkbox" name="chk_regions[]" value="' . $reg . '"';
	if(empty($valid_regions) or in_array($reg,$valid_regions)) echo ' checked="checked"';
	echo ' />' . $reg . '<br />';
} echo '</div></div>';

echo '<div class="topform"><input type="submit" name="submit" value="Update Table" /></div>';
echo '</form><div style="clear:both;"></div>';

// echo buffered output only after the first form submit is made
if($_POST['submit'] == 'Update Table') echo $echo;
?>
</body>
</html>


